package cc.co.cutenimy.nimyexplore.model.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.io.FileUtils;

import cc.co.cutenimy.nimyexplore.model.connection.ConnectionOptions;
import cc.co.cutenimy.nimyexplore.model.jdbc.ConnectionInstance;

import com.google.inject.Singleton;

/**
 * Generate the jdbc connect properties from ConnectionOptions
 * 
 * @author 234aini@gmail.com
 * 
 */
@Singleton
public class ConnectionOptionsGenerator {

	/**
	 * Use the option as key and the string as the value.
	 * 
	 * @param options
	 * @return
	 * @throws JAXBException
	 * @throws IOException
	 */
	public ConnectionOptions from(final InputStream optionXml)
			throws JAXBException, IOException {
		JAXBContext jc = JAXBContext
				.newInstance("cc.co.cutenimy.nimyexplore.model.connection");
		Unmarshaller unmarshaller = jc.createUnmarshaller();
		@SuppressWarnings("unchecked")
		JAXBElement<ConnectionOptions> element = (JAXBElement<ConnectionOptions>) unmarshaller
				.unmarshal(optionXml);
		ConnectionOptions connectionOptions = element.getValue();
		optionXml.close();
		return connectionOptions;
	}

	public ConnectionInstance assemble(final ConnectionOptions options) {
		if (options == null) {
			throw new IllegalArgumentException("The options can't be empty");
		}
		return new ConnectionInstance(options);
	}

	@SuppressWarnings("unchecked")
	public List<ConnectionOptions> loadFrom(final String diskPath) {
		Collection<File> listFiles = FileUtils.listFiles(new File(diskPath),
				new String[] { "xml" }, true);
		if (listFiles.size() <= 0) {
			return Collections.EMPTY_LIST;
		}
		List<ConnectionOptions> opts = new ArrayList<ConnectionOptions>(
				listFiles.size());
		for (File con : listFiles) {
			try {
				opts.add(from(new FileInputStream(con)));
			} catch (Exception e) {
				// ignore this file and continue to next one
			}
		}
		return opts;
	}
}
